<template>
	<view>
		<view class="history-tips" v-if="ajax.loading">
			{{ajax.loadText}}
		</view>
		<!-- :style="{paddingBottom:(bottomZwHeight + 80) + 'px'}" -->
		<view class="message" @tap="togglePicker(0)" @mousemove="togglePicker">
			<view class="message-content" ref="msgContentRef">
				<view v-for="(item,index) in chatList" :key="index" :id="`msg-${item.msgId}`"
					@mousedown.longpress="handleLongPress">
					<chat-msg-item :chatItem="item" :chatItemIndex="index" @showImg="showImg" @showRedPkg="showRedPkg"
						@gotoUserSet="gotoUserSet" @handleAudio="handleAudio" @longpressItem="longpressItem">

						<!-- 时间处理器 -->
						<template v-slot:chatTime>
							<view>{{computeDate(item.time , index)}}</view>
						</template>
					</chat-msg-item>
				</view>
			</view>
		</view>
		<view class="send" v-if="!isShowSend">
			<!-- <view class="send-new-msg" @click="gotoBottomByTips"
				:style="{'visibility':newMsgVisibility,'opacity':newMsgOpacity}">
				<text>有新消息</text>
			</view> -->

			<view class="send-content send-row">
				<view class="send-icon">
					<image src="../common/img/send/voice.svg" v-if="isEdit" @tap="isEdit = false"></image>
					<image src="../common/img/send/keyboard.svg" v-else @tap="isEdit = true"></image>
				</view>
				<input v-if="isEdit" v-model="content" class="send-input" placeholder="请文明发言..." :cursor-spacing="40"
					:adjust-position="isAdjustPosition" confirm-type="send" @confirm="sendMessage"
					@input="textareaBInput" @focus="inputFocus" :focus="isFocus" />

				<view v-else @touchstart="micTouchStart" @touchmove="micTouchMove" @touchcancel="micTouchCancel"
					@touchend="micTouchEnd" class="send-input" style="text-align: center;">
					按住开吼
				</view>
				<button class="send-button" @tap="sendMessageByBtn" v-if="content.length > 0 && isEdit">发送</button>
			</view>
			<view class="send-tool">
				<view v-for="(item,index) in toolList" :key="index" class="file-box" @tap="sendToolTap(item)">
					<image :src="item.img"></image>
				</view>
			</view>
			<!-- <view class="send-zw" :style="{height:bottomZwHeight + 'px'}"></view> -->
		</view>
		<view class="send" v-else>
			<view class="send-content send-row">
				<view class="send-icon">
					<image src="../common/img/send/voice-off.svg"></image>
				</view>
				<view class="send-input" style="text-align: center;">
					{{sendTitle}}
				</view>
			</view>
			<view class="send-tool">
				<view v-for="(item,index) in toolList" :key="index" class="file-box">
					<image :src="item.img"></image>
				</view>
			</view>
		</view>

		<!-- 5，长按弹框 -->
		<chat-con-tool :popButton="popButton" :showShade="showShade" :showPop="showPop" :popStyle="showHeightStyle"
			@pickerMenu="pickerMenu" @hidePop="closeShowTool"></chat-con-tool>

		<!-- 7，发送语音动画 -->
		<chat-voice-icon :isShow="isShowVoiceIcon" :titleText="voiceIconTitle"
			:voiceBgColor="voiceBgColor"></chat-voice-icon>

		<!-- 红包信息 -->
		<chat-redpkg-animation @closeHbFun="closeHbFun" :showHbMsg="showHbMsg" :rbagmodelshow="isShowHb"
			@openHbFun="openHbFun" :openbrnanimation="openbrnanimation" :openrbagmodelshow="openrbagmodelshow"
			@gotoDetail="gotoDetail"></chat-redpkg-animation>

		<chat-add v-if="!isGx" @sendAddUser="sendAddUser"></chat-add>
	</view>
</template>

<script>
	//1，引入公共组件
	import chatSendEmoji from '@/components/content/my-new-chat/child/chat-send-emoji.vue'
	import chatMsgItem from '@/components/content/my-new-chat/child/chat-msg-item.vue'
	import chatConTool from '@/components/content/my-new-chat/child/chat-con-tool.vue'
	import chatAdd from '@/components/content/my-new-chat/child/chat-add.vue'
	import chatVoiceIcon from '@/components/content/my-new-chat/child/chat-voice-icon/index.vue'
	import chatAtAnimation from '@/components/content/my-new-chat/child/chat-at-animation.vue'
	import chatRedpkgAnimation from '@/components/content/my-chat/common/chat-redpkg/redpkg-animation.vue'

	//2，引入vuex
	import {
		mapState,
		mapMutations,
		mapActions,
		mapGetters
	} from 'vuex'

	//3，时间工具处理
	import {
		handleTime,
		timeago
	} from '@/components/content/my-new-chat/utils/time.js'
	import {
		getNowTime
	} from '@/utils/time/time.js'

	//4，引入uniapp工具
	import {
		chooseIamge,
		chooseImageFromCamera
	} from '@/api/uniapp/uni.js'

	//5，引入文件网络请求
	import {
		uploadFile
	} from '@/api/http/common.js'

	//6，引入网络请求
	import {
		queryFriendRemarks
	} from '@/api/http/msg/friend.js'
	import {
		queryRedPkgById,
		robByUser
	} from '@/api/http/msg/redpkg.js'
	import {
		queryIsBlack
	} from '@/api/http/msg/relation.js'

	//7，引入实体类对象
	import {
		msgHomeData,
		msgChatData
	} from '@/object/msg.js'

	//8，语音发送参数
	var recordManager = null;
	var recordTimeInterval = null;

	export default {
		components: {
			chatSendEmoji,
			chatMsgItem,
			chatConTool,
			chatAdd,
			chatVoiceIcon,
			chatAtAnimation,
			chatRedpkgAnimation
		},
		data() {
			return {
				allChatList: [], //所有的聊天信息
				chatList: [], //聊天主要信息
				chatImgs: [], //图片信息

				ajax: {
					pageSize: 1000, //每页数量
					pageNum: 1, //页码
					flag: true, // 请求开关
					loading: true, // 加载中
					loadText: '正在获取消息'
				},
				content: '', // 输入框
				isFocus: false, //输入框获取焦点

				//我的相关信息
				userId: uni.getStorageSync('userId'),
				head: uni.getStorageSync('head'),
				nickname: uni.getStorageSync('nickname'),
				myNickname: uni.getStorageSync('nickname'),
				//聊天对象信息
				friendName: '', //群聊名称
				msgObjectData: {}, //聊天对象信息

				isGx: true, //是否为互相为好友
				isBlackUser: false, //对方是否将你加入黑名单
				isMe: false, //是否为自己
				isShowSend: false, //是否展示禁言框
				sendTitle: '添加好友后聊天', //禁言标题

				//工具展示
				toolList: [{
					id: 1,
					text: '相机',
					img: require('../common/img/file/02.svg')
				}, {
					id: 2,
					text: '拍照',
					img: require('../common/img/file/03.svg')
				}, {
					id: 3,
					text: '红包',
					img: require('../common/img/file/04.svg')
				}],

				isEdit: true, //语音和文本切换
				isAdjustPosition: true, //打开软键盘，是否将页面网上顶

				showPopChatItem: {}, //长按操作的对象
				//长按弹出
				showShade: false,
				showPop: false,
				showHeightStyle: '',
				popButton: [{
					id: 1,
					text: '撤回',
					img: require('@/static/img/msg/tool/01.svg')
				}, {
					id: 2,
					text: '删除',
					img: require('@/static/img/msg/tool/02.svg')
				}],

				//页面宽高信息
				screenHeight: 0,
				windowWidth: 0,
				windowHeight: 0,
				messageHeight: 0, //消息列表所占高度
				//底部输入框高度
				sendHeight: 80,

				//红包信息
				showHbMsg: {},
				isShowHb: false,
				openbrnanimation: {}, //红包点击动画
				openrbagmodelshow: false,

				//发送语音参数
				voiceIconTitle: '正在录音...', //语音动画下的文字
				voiceBgColor: '#05C160', //录音动画背景颜色
				//voiceTime: 0, //语音计时
				voiceInterval: '', //语音定时器
				recorderManager: uni.getRecorderManager(), //录音参数
				recordTime: 0, //语音时间
				isRecording: false, //开启语音发送
				isShowVoiceIcon: false, //是否按住语音说话按钮

				//语音播放
				innerAudioContent: uni.createInnerAudioContext(),

				//当前滚动位置
				nowScrollTop: 0,
				msgContentHeight: 0,
				isgotoBottom: true, //是否收到新消息需要滚动到底部

				newMsgVisibility: 'hidden',
				newMsgOpacity: 0,

				bottomZwHeight: 0,

				isActionListen: false //是否开始监听消息

			}
		},
		mounted() {
			this.$nextTick(() => {
				this.startVoice();
				this.getPageInfo();
			});
		},
		onLoad(e) {
			var msgObject = JSON.parse(e.msgObject)

			this.msgObjectData = msgObject

			this.getChatByPageList(msgObject)

			//消息已读
			this.msgReag(msgObject)

			//获取聊天对象信息
			this.getUserInfo(msgObject.id)

			wx.setNavigationBarTitle({
				title: msgObject.nickname
			})

			//消息监听
			//this.listenSocketMsg()
		},
		onPageScroll(e) {
			//console.log(e.scrollTop)
			if (e.scrollTop < 5) {
				this.getHistoryMsg();
			}
			//时刻更新 滚动位置

			var that = this
			setTimeout(() => {
				var nowDistanceBottom = that.msgContentHeight - e.scrollTop - that.messageHeight
				if (nowDistanceBottom > 200) {
					that.isgotoBottom = false
				} else {
					that.isgotoBottom = true
				}
			}, 30)

		},
		activated() {
			//this.gotoScrollBottom(50)
		},
		onShow() {
			//消息已读
			this.msgReag(this.msgObjectData)
			this.listenSocketMsg()
		},
		onNavigationBarButtonTap(e) {
			if (this.isCanSend) {
				return uni.navigateTo({
					url: '/subpkg/msg/set/set-user/set-user?msgObject=' + JSON.stringify(this.msgObjectData)
				})
			}
		},
		onHide() {
			console.log('隐藏')
			this.innerAudioContent.stop()
		},
		onBackPress() {
			console.log('隐藏2')
			this.innerAudioContent.stop()
		},
		onUnload() {
			console.log('隐藏3')
			this.innerAudioContent.stop()
		},
		computed: {
			...mapState('m_chat', ['chatData', 'topMsgData', 'notTopMsgData']),
			...mapGetters('m_chat', ['getChatData']),
		},
		methods: {
			...mapActions('m_chat', ['setMsgList', 'msgReag', 'msgGoTop', 'clearMsgByList', 'addChatData',
				'readRedPkgStore', 'removeMsvById'
			]),
			//0，获取页面高度
			getPageInfo() {
				uni.getSystemInfo({
					success: (res) => {
						this.$nextTick(() => {
							//页面可用高度
							this.screenHeight = res.windowHeight
							this.windowWidth = res.windowWidth
							this.windowHeight = res.windowHeight

							//计算，消息列表高度
							this.messageHeight = res.windowHeight - 80
						})
					}
				})
			},
			//1，查询页面聊天消息
			getChatByPageList(msgObjectData) {
				//1，遍历所有的聊天信息
				for (var i = 0; i < this.chatData.length; i++) {
					if (this.chatData[i].id == msgObjectData.id &&
						this.chatData[i].type == msgObjectData.type) {
						//2，获取当前聊天的总聊天信息
						var newChatData = this.chatData[i].list

						/* if (newChatData.length == 0) {
							console.log('没有消息')
							return
						} */
						//console.log(newChatData)
						this.allChatList = newChatData
						this.getHistoryMsg()
						return
					}
				}

				this.getHistoryMsg()

			},
			//1.1，获取历史消息
			getHistoryMsg() {
				if (!this.ajax.flag) {
					return; //
				}
				var that = this
				// 此处用到 ES7 的 async/await 知识，为使代码更加优美。不懂的请自行学习。
				let get = async () => {
					this.hideLoadTips();
					this.ajax.flag = false;
					//获取到了新的消息
					let data = await this.joinHistoryMsg();

					if (data.length == 0) {
						console.log('没有更多信息！')
						this.ajax.loadText = '没有历史消息';
						setTimeout(() => {
							this.ajax.loading = false;
						}, 700);
						return
					}

					for (var i = 0; i < data.length; i++) {
						if (data[i].msgType == 2) {
							that.chatImgs.push(data[i].news)
						}
					}

					// 获取待滚动元素选择器，解决插入数据后，滚动条定位时使用
					let selector = '';

					if (this.ajax.pageNum > 1) {
						// 非第一页，则取历史消息数据的第一条信息元素
						selector = `#msg-${this.chatList[0].msgId}`;
					} else {
						// 第一页，则取当前消息数据的最后一条信息元素
						selector = `#msg-${data[data.length-1].msgId}`;
					}

					// 将获取到的消息数据合并到消息数组中
					this.chatList = [...data, ...this.chatList];

					// 数据挂载后执行，不懂的请自行阅读 Vue.js 文档对 Vue.nextTick 函数说明。
					this.$nextTick(() => {
						// 设置当前滚动的位置
						this.setPageScrollTo(selector);

						this.hideLoadTips(true);

						if (data.length < this.ajax.pageSize) {
							// 当前消息数据条数小于请求要求条数时，则无更多消息，不再允许请求。
							// 可在此处编写无更多消息数据时的逻辑
							var that = this
							setTimeout(() => {
								// 重新加载消息列表高度
								uni.createSelectorQuery().in(this).select('.message-content')
									.boundingClientRect((rect) => {
										that.msgContentHeight = rect.height
										//console.log(rect.height)
									}).exec()
							}, 200)
						} else {
							this.ajax.pageNum++;

							var that = this
							// 延迟 200ms ，以保证设置窗口滚动已完成
							setTimeout(() => {
								this.ajax.flag = true;

								// 重新加载消息列表高度
								uni.createSelectorQuery().in(this).select('.message-content')
									.boundingClientRect((rect) => {
										that.msgContentHeight = rect.height
										//console.log(rect.height)
									}).exec()
							}, 100)
						}

					})

				}
				get();
			},
			//1.2，拼接历史记录消息，正式项目可替换为请求历史记录接口
			joinHistoryMsg() {
				var that = this
				let join = () => {
					let arr = [];

					//1，计算从第几条开始
					var startIndex = (that.ajax.pageNum - 1) * that.ajax.pageSize
					var endIndex = that.ajax.pageNum * that.ajax.pageSize
					if (that.allChatList.length == 0) {
						return []
					}
					//2，获取新的历史消息
					arr = that.allChatList.slice(startIndex, endIndex)
					//console.log(arr)
					if (arr.length == 0) {
						//this.isShowHistoryMsgTips = false
						return []
					}
					/*
						颠倒数组中元素的顺序。将最新的数据排在本次接口返回数据的最后面。
						后端接口按 消息的时间降序查找出当前页的数据后，再将本页数据按消息时间降序排序返回。
						这是数据的重点，因为页面滚动条和上拉加载历史的问题。
					 */
					arr.reverse();
					return arr;
				}

				// 此处用到 ES6 的 Promise 知识，不懂的请自行学习。
				return new Promise((done, fail) => {
					// 无数据请求接口，由 setTimeout 模拟，正式项目替换为 ajax 即可。
					//let data = join();
					setTimeout(() => {
						let data = join();
						done(data);
					}, 500);
				})
			},
			//1.3，隐藏消息加载提示
			hideLoadTips(flag) {
				if (flag) {
					this.ajax.loadText = '消息获取成功';
					setTimeout(() => {
						this.ajax.loading = false;
					}, 300);
				} else {
					this.ajax.loading = true;
					this.ajax.loadText = '正在获取消息';
				}
			},

			//2，设置页面滚动位置
			setPageScrollTo(selector) {
				let view = uni.createSelectorQuery().in(this).select(selector);
				view.boundingClientRect((res) => {
					uni.pageScrollTo({
						scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度，示意上面还有信息。
						duration: 0
					});
				}).exec();
			},

			//3，时间格式化
			computeDate(createTime, index) {
				if (createTime) {
					if (uni.getSystemInfoSync().platform === 'android') {
						//console.log('运行Android上')
						var datetime = new Date(createTime)
						let date = new Date()

						if (index > 0) {
							//获取上一个
							let beforetime = this.chatList[index - 1].time
							let beforetimestrap = new Date(beforetime)
							if ((datetime - beforetimestrap) > 180000) {
								return this.getTime(createTime)
							} else {
								return ''
							}
						} else {
							return this.getTime(createTime)
						}

					} else {
						//console.log('运行iOS上')
						var datetime = new Date(createTime.replace(/-/g, '/'))
						let date = new Date()

						if (index > 0) {
							//获取上一个
							let beforetime = this.chatList[index - 1].time
							let beforetimestrap = new Date(beforetime.replace(/-/g, '/'))
							if ((datetime - beforetimestrap) > 180000) {
								return this.getTime(createTime.replace(/-/g, '/'))
							} else {
								return ''
							}
						} else {
							return this.getTime(createTime.replace(/-/g, '/'))
						}
					}
				} else {
					return ''
				}
			},
			//3.1，获取时间
			getTime(time) {
				if (uni.getSystemInfoSync().platform === 'android') {
					//console.log('运行Android上')
					return handleTime(time)
				} else {
					//console.log('运行iOS上')
					return handleTime(time.replace(/-/g, '/'))
				}
			},

			//4，获取聊天对象信息
			getUserInfo(fid) {
				if (fid == this.userId) {
					this.isMe = true
					return
				}
				var that = this
				queryFriendRemarks(parseInt(fid), 2).then(res => {
					if (res.data.pubInfo.code !== 0) {
						//uni.$showMsg(res.data.pubInfo.message);
						if (res.data.pubInfo.message == '未建立关系') {
							that.isGx = false
							that.isShowSend = true
						}
						return
					}
					//2.3，参数保存
					var busInfo = res.data.busInfo
					that.friendName = busInfo

					wx.setNavigationBarTitle({
						title: busInfo
					})

					queryIsBlack(that.userId, fid).then(res => {
						if (res.data.pubInfo.code !== 0) {
							return uni.$showMsg(res.data.pubInfo.message)
						}
						//console.log(res.data.busInfo)
						if (res.data.busInfo == '2') {
							that.isBlackUser = true
						}

						//消息置顶
						//that.$refs.myChatRef.closeRefreshScroll()
					})
				})
			},

			//5，工具点击
			sendToolTap(item) {
				if (item.id == 1) {
					this.chooseIamgeFromAlbum()
				} else if (item.id == 2) {
					this.chooseIamgeFromCamera()
				} else {
					//发送红包
					if (!uni.getStorageSync('identifyCheck')) {
						return uni.$showMsg('请先进行实名认证！')
					}

					uni.navigateTo({
						url: '/subpkg/msg/red-pkg/red-pkg-send/red-pkg-send?msgObject=' + JSON.stringify(this
							.msgObjectData)
					})
				}
			},
			//5.1，发送图片
			chooseIamgeFromAlbum() {
				var that = this
				chooseIamge('album').then(res => {
					const filePaths = res.tempFilePaths
					for (let i = 0; i < filePaths.length; i++) {
						//图片上传
						uploadFile(filePaths[i]).then(result => {
							if (result.data.pubInfo.code !== 0) {
								return uni.$showMsg(result.data.pubInfo.message);
							}
							//var  = result.data.busInfo
							that.sendMsgByUser(result.data.busInfo, 2)
						})
					}
				})
			},
			//5.2，照相发送
			chooseIamgeFromCamera() {
				var that = this
				chooseImageFromCamera().then(res => {
					uploadFile(res).then(result => {
						if (result.data.pubInfo.code !== 0) {
							return uni.$showMsg(result.data.pubInfo.message);
						}
						//var  = result.data.busInfo
						that.sendMsgByUser(result.data.busInfo, 2)
					})
				})
			},

			//6，输入框
			//6.1，输入框发送信息
			sendMessage(e) {
				if (e.detail.value == '' || e.detail.value == null) {
					return
				}
				this.sendMsgByUser(e.detail.value, 1)
				//清空聊天框
				this.content = ''

				/* setTimeout(() => {
					//清空聊天框
					this.content = ''
				}, 10) */
			},
			//6.2，按钮发送
			sendMessageByBtn() {
				if (this.content == '' || this.content == null) {
					return
				}
				this.sendMsgByUser(this.content, 1)
				//清空聊天框
				this.content = ''
			},
			//6.3，输入框获取焦点
			inputFocus(e) {
				var iosHeight = uni.getSystemInfoSync().safeAreaInsets
				//console.log(iosHeight)
				//console.log(e.detail.heigh)
				this.bottomZwHeight = e.detail.heigh

				uni.onKeyboardHeightChange(res => {
					//console.log(res.height)
					this.bottomZwHeight = res.height
				})
			},

			//6.5，文本输入监听
			textareaBInput(e) {

			},

			//7，查看图片
			showImg(e) {
				var that = this
				uni.previewImage({
					current: e.news,
					urls: this.chatImgs,
					longPressActions: {
						itemList: ['保存图片'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');

							uni.downloadFile({
								url: that.chatImgs[data.index],
								success: (res) => {
									if (res.statusCode === 200) {
										uni.saveImageToPhotosAlbum({
											filePath: res.tempFilePath,
											success: function() {
												//uniapp提供的消息提示框。
												uni.showToast({
													title: "保存成功",
													icon: "success"
												});
											},
											fail: function() {
												uni.showToast({
													title: "保存失败，请稍后重试",
													icon: "none"
												});
											}
										});
									}
								}
							})

						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				})
			},
			//8，点击好友头像设置
			gotoUserSet(item) {
				if (item.sendId == this.userId) {
					//用户点击自己的头像
					return
				}
				var req = {
					id: item.sendId,
					nickname: item.sendNickname,
					head: item.sendHead,
					type: 2, //用户单聊类型
				}
				uni.navigateTo({
					url: '/subpkg/msg/user/user-describe/user-describe?msgObject=' + JSON.stringify(req),
				})
			},

			//9，长按弹框
			longpressItem(item, chatItem, viewId) {
				
				/* var view = document.getElementById(id)
				view.style.backgroundColor = 'red'; */
				
				//console.log(item)
				//console.log(chatItem)
				if (chatItem.isWithdraw && chatItem.sendId == this.userId) {
					//可以撤回
					this.popButton = [{
						id: 1,
						text: '撤回',
						img: require('@/static/img/msg/tool/01.svg')
					}, {
						id: 2,
						text: '删除',
						img: require('@/static/img/msg/tool/02.svg')
					}]
				} else {
					//无法撤回
					this.popButton = [{
						id: 2,
						text: '删除',
						img: require('@/static/img/msg/tool/02.svg')
					}]
				}

				this.showPopChatItem = chatItem
				//计算光标高度（距离顶部导航栏的距离）
				var height = parseInt(item.pageY)
				var width = parseInt(item.pageX)
				var bottomHeight = (this.windowHeight - this.sendHeight - 50)
				var leftWidth = this.windowWidth * 0.7
				var rightWidth = this.windowWidth * 0.22
				//this.windowWidth - width
				/* console.log(bottomHeight)
				console.log(height) */
				if (height < 45) {
					//1，如果小于弹框高度则固定位置
					if (width > leftWidth) {
						this.showHeightStyle = `top:60px;right:${rightWidth}px;`
					} else {
						this.showHeightStyle = `top:60px;left:${width}px;`
					}
				} else if (bottomHeight < height) {
					//2，如果，在底部的话则固定在上面
					if (width > leftWidth) {
						this.showHeightStyle = `bottom:${this.sendHeight + 30}px;right:${rightWidth}px;`
					} else {
						this.showHeightStyle = `bottom:${this.sendHeight + 30}px;left:${width}px;`
					}
				} else {
					if (width > leftWidth) {
						this.showHeightStyle = `top:${height}px;right:${rightWidth}px;`
					} else {
						this.showHeightStyle = `top:${height}px;left:${width}px;`
					}
				}
				console.log(this.showHeightStyle)
				this.showShade = true;
				this.$nextTick(() => {
					setTimeout(() => {
						this.showPop = true;
					}, 10);
				});
			},
			//9.1，关闭弹框
			closeShowTool() {
				this.showPop = false;
				//this.pickerUserIndex = -1;
				setTimeout(() => {
					this.showShade = false;
				}, 10);
			},
			//9.2选择其中的一个
			pickerMenu(item) {
				//console.log(this.showPopChatItem)
				if (item.id == 2) {
					this.closeUserMsg(this.showPopChatItem)
					//this.$emit('closeUserMsg', this.showPopChatItem)
				} else {
					this.withdrawUserMsg(this.showPopChatItem)
					//this.$emit('withdrawUserMsg', this.showPopChatItem)
				}
			},
			//9.3，删除消息
			closeUserMsg(showPopChatItem) {
				//删除消息
				for (var i = 0; i < this.chatList.length; i++) {
					if (this.chatList[i].msgId == showPopChatItem.msgId) {
						this.chatList.splice(i, 1)
						continue;
					}
				}
				this.removeMsvById(showPopChatItem)
				return
			},
			//9.4，撤回消息
			withdrawUserMsg(showPopChatItem) {
				let data = {
					msg: '撤回一条消息',
					types: 11
				}
				this.socketSendMsg(data, showPopChatItem.msgId)
			},

			//10.1，点击红包消息
			showRedPkg(item) {
				//判断是否实名认证 如果没有实名认证无法下单
				if (!uni.getStorageSync('identifyCheck')) {
					return uni.$showMsg('请先进行实名认证！')
				}
				//console.log(item)
				//this.isShowHb = true
				this.showHbMsg = item
				if (!item.isRedRead) {
					var req = item
					req.type = 2
					req.id = this.msgObjectData.id
					//红包已读
					this.readRedPkgStore(req)
				}

				if (this.userId != item.sendId) {
					queryRedPkgById(item.redPkgId).then(res => {
						if (res.data.pubInfo.code !== 0) {
							return uni.$showMsg(res.data.pubInfo.message);
						}
						//2.3，参数保存
						var busInfo = res.data.busInfo
						if (busInfo.surplusAmount > 0 && busInfo.surplusNum > 0) {
							//如果不是自己发送的红包（展示抢红包特效）
							this.isShowHb = true
						} else {
							//没有剩余红包，直接跳转红包详情页
							return uni.navigateTo({
								url: '/subpkg/msg/red-pkg/red-pkg-detail/red-pkg-detail?hbId=' + item
									.redPkgId
							})
						}
						//console.log(busInfo)
					})

				} else {
					//如果是自己发的红包直接跳转红包详情页面
					uni.navigateTo({
						url: '/subpkg/msg/red-pkg/red-pkg-detail/red-pkg-detail?hbId=' + item.redPkgId +
							'&nickname=' + this.friendName
					})

				}
			},
			//10.2，关闭红包
			closeHbFun() {
				this.isShowHb = false
			},
			//10.3，开始抢红包
			openHbFun(item) {
				var that = this;
				var animation = uni.createAnimation({
					duration: 1000,
					timingFunction: 'ease',
				})
				that.openbrnanimation = animation;
				// animation.rotate3d(0,1,0,360).step();
				animation.rotateY(360).step();
				that.openbrnanimation = animation.export();
				robByUser(item.redPkgId).then(res => {
					if (res.data.pubInfo.code !== 0) {
						return uni.$showMsg(res.data.pubInfo.message);
					}
					that.isShowHb = false
					//that.rbagmodelshow = false;
					that.openrbagmodelshow = true;
					that.openbrnanimation = {};

					//跳转到详情页面
					setTimeout(() => {
						return uni.navigateTo({
							url: '/subpkg/msg/red-pkg/red-pkg-detail/red-pkg-detail?hbId=' + item
								.redPkgId + '&nickname=' + this.friendName
						})
					}, 500)

				})
			},
			//10.4，查看红包
			gotoDetail(item) {
				/* var redPkgMsgInfo = {
					redPkgId: item.redPkgId,
					identity: this.groupInfo.identity,
					protect: this.groupInfo.protect
				} */

				/* return uni.navigateTo({
					url: '/subpkg/msg/red-pkg/red-pkg-group/red-pkg-group?redPkgMsgInfo=' + JSON
						.stringify(redPkgMsgInfo)
				}) */
			},

			//11，启动语音发送
			startVoice() {
				this.$nextTick(() => {
					recordManager = uni.getRecorderManager()
					recordManager.onStart(() => {
						console.log('开启动画')
						//展示语音动画
						this.isShowVoiceIcon = true

						recordTimeInterval = setInterval(() => {
							this.recordTime += 1;
							//this.formatedRecordTime = util.formatTime(this.recordTime)

							if (this.recordTime > 10) {
								//结束计时
								clearInterval(recordTimeInterval)
								this.micTouchEnd()
							}
						}, 1000)
					})
					recordManager.onStop((res) => {
						if (this.isCancel) {
							//this.formatedRecordTime = "00:00:00"
							this.isCancel = false
							this.recordTime = 0
						} else {
							if (this.recordTime < 1) {
								this.recordTime = 0
								//console.log('时间太短')
								uni.showToast({
									icon: 'none',
									title: '发送时间太短',
									duration: 1000
								})
								return
							} else {

								uploadFile(res.tempFilePath).then(result => {
									if (result.data.pubInfo.code !== 0) {
										this.isShowClose = false
										this.isShowVoiceIcon = false;
										//归为时长
										this.recordTime = 0
										return uni.$showMsg(result.data.pubInfo.message);
									}
									//var  = result.data.busInfo
									let data = {
										voice: result.data.busInfo,
										time: this.recordTime,
										//标识是否执行
										anmitionPlay: false
									}
									//console.log(result.data.busInfo)
									this.sendMsgByUser(JSON.stringify(data), 3)
									//this.$emit('sendMsgByUser', JSON.stringify(data), 3)
									this.recordTime = 0
								})
							}
						}
					})
				})
			},
			//11.1，按住说话
			micTouchStart(e) {
				// #ifdef APP-PLUS
				plus.device.vibrate(50); //震动
				// #endif

				this.isRecording = true
				recordManager.start({
					format: 'mp3'
				})
			},
			micTouchMove(e) {
				//距离顶部位置
				const pointY = e.touches[0].clientY
				//console.log(this.windowHeight)
				if ((this.windowHeight - 100) > pointY) {
					this.voiceIconTitle = '松开取消发送'
					//console.log('松开')
					this.voiceBgColor = '#FA5251'


					this.isShowClose = true
					this.isCancel = true
				} else {
					this.voiceIconTitle = '正在录音... '
					this.voiceBgColor = '#05C160'

					this.isShowClose = false
					this.isCancel = false
				}
			},
			micTouchCancel(e) {
				this.isRecording = false
				clearInterval(recordTimeInterval)
				recordManager.stop()
				this.isShowVoiceIcon = false;
				this.isShowClose = false

				//this.voiceTime = 0;
				this.voiceIconTitle = '按住 说话';
				this.voiceBgColor = '#05C160'
			},
			micTouchEnd(e) {
				this.isRecording = false
				clearInterval(recordTimeInterval)
				recordManager.stop()
				this.isShowVoiceIcon = false;
				this.isShowClose = false

				//this.voiceTime = 0;
				this.voiceIconTitle = '按住 说话';
				this.voiceBgColor = '#05C160'

			},

			//12，语音播放
			handleAudio(item) {
				this.innerAudioContent.paused ? this.playAudio(item) : this.stopAudio(item);

				this.innerAudioContent.onPlay(() => {
					//console.log('播放')
					//this.innerAudioContent.paused = false
				})

				this.innerAudioContent.onEnded(() => {
					//console.log('暂停播放')
					//this.innerAudioContent.paused = true
					this.stopAudio(item)
				})
			},
			//12.1，播放音频
			playAudio(item) {
				//console.log(item)
				var voice = JSON.parse(item.news)
				var voiceUrl = voice.voice
				this.innerAudioContent.src = voiceUrl
				this.innerAudioContent.play()

				for (var i = 0; i < this.chatList.length; i++) {
					if (this.chatList[i].msgId == item.msgId && this.chatList[i].time == item.time) {
						var oldVoice = JSON.parse(this.chatList[i].news)
						oldVoice.anmitionPlay = true
						this.chatList[i].news = JSON.stringify(oldVoice)
					}
				}

			},
			//12.2，停止音频
			stopAudio(item) {
				var voice = JSON.parse(item.news)
				this.innerAudioContent.src = ''
				this.innerAudioContent.stop()
				for (var i = 0; i < this.chatList.length; i++) {
					if (this.chatList[i].msgId == item.msgId && this.chatList[i].time == item.time) {
						var oldVoice = JSON.parse(this.chatList[i].news)
						oldVoice.anmitionPlay = false
						this.chatList[i].news = JSON.stringify(oldVoice)
					}
				}
			},

			//13，有新的消息，展示新的消息提示框
			showNewTips() {
				this.newMsgVisibility = 'visible'
				this.newMsgOpacity = 1
			},
			//13.2，关闭
			closeNewTips() {
				this.newMsgVisibility = 'hidden'
				this.newMsgOpacity = 0
			},

			//14，关闭软键盘
			togglePicker() {
				//隐藏键盘
				uni.hideKeyboard()
			},
			//15，发起添加好友请求
			sendAddUser() {
				var reqData = {
					type: this.$chatType.ADD_FRIEND,
					msg: {
						senderId: this.userId,
						senderName: this.nickname,
						senderHead: this.head,
						receiverId: this.msgObjectData.id,
						message: '添加好友',
						sysType: 2,
					}
				}

				uni.myWebsocket.socketTask.send({
					data: JSON.stringify(reqData),
					async success() {
						return uni.$showMsg('发送成功');
					},
					fail(e) {
						uni.$showMsg('发送失败！');
					}
				});
			},

			handleLongPress(event) {
				const target = event.target; // 获取触发事件的元素

				const id = target.getAttribute('id'); // 获取绑定的id
				const className = target.className; // 获取绑定的class

				console.log("ID:", id);
				console.log("Class:", className);

			},

			//0，发送消息给指定用户
			sendMsgByUser(msg, types) {
				var data = {
					types,
					msg
				}
				this.socketSendMsg(data, 0)
			},
			//1，socket发送消息
			socketSendMsg(e, msgId) {
				if (!this.isGx) {
					return uni.$showMsg('对方不是你的好友！');
				}
				if (this.isBlackUser) {
					return uni.$showMsg('对方已将您加入黑名单！');
				}

				var that = this
				var nowTime = getNowTime() + ''

				//消息组装
				let msgData = {
					type: this.$chatType.CHAT_FRIEND,
					msg: {
						id: msgId || 0,
						senderId: this.userId,
						senderHead: this.head, //头像
						senderName: this.nickname,
						types: e.types, //消息类型 （1文本，2图片连接，3音频，4红包）
						message: e.msg, //消息 
						time: nowTime,
						receiverId: this.msgObjectData.id,
						receiverHead: this.msgObjectData.head,
						receiverName: this.msgObjectData.nickname
					}
				}
				//console.log(msgData)
				uni.myWebsocket.socketTask.send({
					data: JSON.stringify(msgData),
					async success() {
						console.log('发送成功')
					},
					fail(e) {
						uni.$showMsg('发送失败！');
						console.log(e)
					}
				});
			},
			//2，消息监听
			listenSocketMsg() {
				if (uni.myWebsocket == undefined || uni.myWebsocket == '' || uni.myWebsocket == null || uni.myWebsocket
					.socketTask.readyState !== 1) {
					//连接上websocket
					this.isActionListen = false
					uni.$connectSocketInit.connectSocket(uni.$nettyPort)
				}

				if (this.isActionListen) {
					console.log('已经开始监听了')
					return
				}

				//消息监听
				var that = this
				uni.myWebsocket.socketTask.onMessage((result) => {
					that.isActionListen = true
					var res = JSON.parse(result.data)
					//console.log(res)
					if (res.type == uni.$chatType.CHAT_FRIEND && (res.params.senderId == that.msgObjectData.id ||
							res.params.receiverId == that.msgObjectData.id)) {
						var resParams = res.params

						var id = res.params.senderId
						var head = res.params.senderHead
						var name = res.params.senderName

						if (res.params.senderId == that.userId) {
							id = res.params.receiverId
							name = res.params.receiverName
							head = res.params.receiverHead
						}

						if (resParams.types == 11) {
							//撤回一条消息
							for (var i = 0; i < that.chatList.length; i++) {
								if (that.chatList[i].msgId == resParams.id) {
									var addMsgChatData = msgChatData(
										res.params.id,
										res.params.tip,
										res.params.message,
										res.params.senderId,
										res.params.senderHead,
										res.params.senderName,
										res.params.types,
										res.params.time + '',
										2,
										id,
										res.params.redPkgId
									)
									that.chatList.splice(i, 1)
									that.chatList.push(addMsgChatData)
								}
							}
							return
						}

						var addMsgChatData = msgChatData(
							res.params.id,
							res.params.tip,
							res.params.message,
							res.params.senderId,
							res.params.senderHead,
							res.params.senderName,
							res.params.types,
							res.params.time + '',
							2,
							id,
							res.params.redPkgId
						)

						that.chatList.push(addMsgChatData);

						that.msgReag(that.msgObjectData)

						if (addMsgChatData.msgType == 2) {
							that.chatImgs.push(addMsgChatData.news)
						}

						if (that.isgotoBottom || res.params.senderId == that.userId) {
							that.$nextTick(() => {
								// 清空内容框中的内容
								that.content = '';
								setTimeout(() => {
									uni.pageScrollTo({
										scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
										duration: 0
									});
								}, 100)

							})
						}

					}

				})

			},
			isContainStr(str1, str2) {
				if (str1 == null || str2 == null) {
					return false
				}
				return (str1.indexOf(str2) !== -1)
			},

		}
	}
</script>

<style lang="scss">
	//@import "../common/css/global.scss";

	@import "../common/css/message.scss";
	@import "../common/css/send.scss";
	@import "../common/css/tips.scss";

	page {
		background-color: #F3F3F3;
		font-size: 28rpx;
	}
</style>